package com.kingmed.kmss.bpmn.modules.backup.controller;

import java.util.ArrayList;
import java.util.List;

import com.kingmed.kmss.bpmn.flow.service.base.BpmNativeServiceImpl;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.kingmed.kmss.bpmn.flow.helper.HistoryHelper;
import com.kingmed.kmss.bpmn.flow.helper.ProcessHelper;
import com.kingmed.kmss.common.bo.bpmn.ProcessDefinitionBO;
import com.kingmed.kmss.common.utils.BeanCopyUtils;
import com.kingmed.kmss.common.utils.MessageUtils;
import com.kingmed.kmss.common.vo.CommonResponse;
import com.kingmed.kmss.common.vo.CommonResponseHelper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 需补充审批功能所需要的流程类接口，包括流程启动，流程终止，流程历史等接口
 * </p>
 */
@RestController
@RequestMapping("/dev/")
@Api(tags = "bpmn-bpmn-开发协助工具")
public class DevUtilsController {

	@Autowired
	private BpmNativeServiceImpl nativeService;
	
	@Autowired
	ProcessHelper procHelper;

	@Autowired
	HistoryHelper historyHelper;
	
	@ApiOperation("获取已部署流程列表-所有版本")
    @PostMapping(value = "/process/")
    public CommonResponse<?> getDeployProcessList() {
   
		return CommonResponseHelper.success(nativeService.getProcesssList());
    }

	@ApiOperation("获取Deployment列表-所有版本")
	@GetMapping(value = "/deployment/")
	public CommonResponse<?> getDeploymentList() {

		return CommonResponseHelper.success(nativeService.getDeployment());
	}

	@ApiOperation("获取已部署流程列表-最新版本")
	@GetMapping(value = "/process/latest")
	public CommonResponse<?> getLatestDeployProcessList() {
	
		return CommonResponseHelper.success(nativeService.getLatestProcesssList());
	}

	/**
	 * 通过删除Deployment来删除相关process - 限测试用
	 * @param deployId
	 * @return
	 */
	@ApiOperation("***慎用***删除已部署流程定义")
	@RequestMapping(value = "/process/deploy/delete", method = RequestMethod.POST)
	public CommonResponse<?> deleteDeployProcessById(@PathVariable(value = "deployId") String deployId) {
		boolean deleted = nativeService.deleteDeployProcessById(deployId);
		if (!deleted) {
			return CommonResponseHelper.fail(MessageUtils.message("bpnm.deploymentNotExist", deployId));			
		}
		return CommonResponseHelper.success(MessageUtils.message("process.deleted"));
	}
	
	/**
	 * 通过删除Deployment来删除相关process - 限测试用
	 * @param deployId
	 * @return
	 */
	@ApiOperation("***慎用***删除所有已部署流程定义")
	@RequestMapping(value = "/process/deploy/delete/all", method = RequestMethod.POST)
	public CommonResponse<?> deleteAllDeploys() {
		int numOfDeletedDeploy = nativeService.deleteAllDeployments();
	
		return CommonResponseHelper.success(MessageUtils.message("process.deleted") + ": " + numOfDeletedDeploy);
	}
	
	@ApiOperation("***慎用***删除未结束流程")
	@RequestMapping(value = "/process/unfinished/delete", method = RequestMethod.POST)
	public CommonResponse<?> deleteUnFinishedprocess(@RequestParam String businessKey,
			@RequestParam String reason) {
		int num = procHelper.cleanupProcessInstByBizKey(businessKey, reason);
		
		return CommonResponseHelper.success(num);
	}
	@ApiOperation("***慎用***删除指定bizType下所有未结束流程")
	@RequestMapping(value = "/process/unfinished/deleteByBizType", method = RequestMethod.POST)
	public CommonResponse<?> deleteUnFinishedprocessByBizType(@RequestParam String bizType,
			@RequestParam String reason) {
		int num = procHelper.cleanupProcessInstByBizType(bizType, reason);
		
		return CommonResponseHelper.success(num);
	}
	@ApiOperation("***慎用***删除所有未结束流程")
	@RequestMapping(value = "/process/unfinished/deleteAll", method = RequestMethod.POST)
	public CommonResponse<?> deleteAllUnFinishedprocess(
			@RequestParam String reason) {
		int num = procHelper.cleanupAllProcessInsts( reason);
		
		return CommonResponseHelper.success(num);
	}
	
	@ApiOperation("列出businessKey下未结束的流程")
	@RequestMapping(value = "/process/instance/list", method = RequestMethod.POST)
	public CommonResponse<?> listInstance(@RequestParam String businessKey) {
	
		return CommonResponseHelper.success(procHelper.getProcessInstsByBizKey(businessKey));
	}
	
	@ApiOperation("列出所有未结束的流程")
	@RequestMapping(value = "/process/instance/uncomplete", method = RequestMethod.POST)
	public CommonResponse<?> allUnCompleteInstance() {
	
		return CommonResponseHelper.success(procHelper.getProcessInsts());
	}

	/**
	 * 入参是bo processDefinitionBO，可以改成仅通过key来查询 测试数据processKey=oneTaskProcess
	 * 备注：某些flowable的原生model，例如ProcessDefinition，直接在controller返回时会发生数据转换异常，建议copy到bo或者dto，再放入CommonResponse
	 */
	@ApiOperation("根据ProcessDefinitionKey查询流程定义(可能有多个)")
	@RequestMapping(value = "/process/define", method = RequestMethod.POST)
	public CommonResponse<?> findProcessDef(@RequestBody ProcessDefinitionBO processDefinitionBO) {
		List<ProcessDefinition> list = nativeService.findProcessInstanceByKey(processDefinitionBO);
		List<ProcessDefinitionBO> result = new ArrayList<>();
		if (!list.isEmpty()) {
			for (ProcessDefinition definition : list) {
				ProcessDefinitionBO item = new ProcessDefinitionBO();
				BeanCopyUtils.copy(definition, item);
				// model和bo，dto之间，字段设计时最好保持一致
				item.setProcessKey(definition.getKey());
				item.setProcessId(definition.getId());
				result.add(item);
			}
		}
		return CommonResponseHelper.success(result);
	}


    @ApiOperation("根据业务类型查询历史")
    @RequestMapping(value = "/history/byCategory", method = RequestMethod.GET)
    public CommonResponse<?> test(@RequestParam(value = "param") String param) {
    	
        return CommonResponseHelper.success(historyHelper.findHistoryByCategory(param));
    }
}
